<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>拖拽效果</title>
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            html,
            body,
            #root {
                width: 100vw;
                height: 100vh;
                overflow: hidden;
            }

            #move {
                width: 150px;
                height: 150px;
                background: rgb(35, 185, 153);
                position: absolute;
                transition: all 0.5s;
            }
        </style>
    </head>
    <body>
        <div id="root">
            <div id="move"></div>
        </div>

        <script>
            let root = document.querySelector("#root");
            let move = document.querySelector("#move");

            root.addEventListener('touchstart', function(e){
                e.preventDefault();
            })

            //绑定事件
            move.addEventListener("touchstart", function (e) {
                //消除过渡
                this.style.transition = 'none';
                //获取手指距离左侧的偏移量
                this.x = e.changedTouches[0].clientX;
                //获取 move 距离左侧的偏移量
                this.l = move.offsetLeft;
                //
                this.y = e.changedTouches[0].clientY;
                this.t = move.offsetTop;
            });

            move.addEventListener("touchmove", function (e) {
                //获取手指滑动之后, 距离左侧的偏移量
                this._x = e.changedTouches[0].clientX;
                this._y = e.changedTouches[0].clientY;
                //计算新的 left 的值
                let newLeft = this._x - (this.x - this.l);
                let newTop = this._y - (this.y - this.t);
                //判断
                if(newLeft <= 0) newLeft = 0;
                //计算最大的left值
                this.maxLeft = document.documentElement.clientWidth - this.offsetWidth;
                //判断
                if(newLeft >= this.maxLeft) newLeft = this.maxLeft;
                //设置元素的样式
                this.style.left = newLeft + 'px';
                this.style.top = newTop + 'px';
                // e.target.style.left = newLeft + 'px';
            });

            move.addEventListener("touchend", function (e) {
                this.style.transition = 'all 0.3s';
                //吸附效果
                // 计算中线时, left 的值
                let middle = (document.documentElement.clientWidth - this.offsetWidth) / 2;
                //判断
                // 获取元素距离左侧的偏移
                let left = this.offsetLeft;
                if(left < middle){
                    this.style.left = '0px';
                }else{
                    this.style.left = this.maxLeft + 'px';
                }
            });
        </script>
    </body>
</html>
